package com.demo.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.dto.Result;
import com.demo.entity.Shop;
import com.demo.mapper.ShopMapper;
import com.demo.service.IShopService;
import com.demo.utils.CacheClient;
import com.demo.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.demo.utils.RedisConstants.*;

@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    //开启一个线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        //解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //逻辑过期解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null){
            return Result.fail("商铺不存在");
        }
        return Result.ok(shop);
    }

    @Override
    @Transactional//通过事务控制原子性
    public Result update(Shop shop) {
        if (shop.getId() == null){
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        String key = CACHE_SHOP_KEY + shop.getId();
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    /**
     * 封装-解决缓存穿透
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id){
        //1.从redis中查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopInfo = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopInfo)){
            //3.存在 返回 将字符转为json形式
            Shop shopJson = JSONUtil.toBean(shopInfo, Shop.class);
            return shopJson;
        }
        //TODO 判断是否为null，如果为空就去数据库中查询，不为空就返回
        if (shopInfo != null){
            return null;
        }

        //4.不存在去数据库查询
        //TODO 缓存穿透（传入一个不存在的id，穿透redis 打入数据库）
        Shop shop = getById(id);
        //5.不存在返回错误信息
        if (shop == null){
            //TODO 防止redis缓存穿透，选择缓存空字符防止继续穿透 设置过期时间防止占满内存
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //6.存在 写入redis 并设置过期时间 转换为Json格式
        String value = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(key,value,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7.返回shop信息
        return shop;
    }

    /**
     * 封装-解决缓存击穿-互斥锁
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id){
        //1.从redis中查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopInfo = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopInfo)){
            //3.存在 返回 将字符转为json形式
            Shop shopJson = JSONUtil.toBean(shopInfo, Shop.class);
            return shopJson;
        }
        //TODO 判断是否为null，如果为空就去数据库中查询，不为空就返回
        if (shopInfo != null){
            return null;
        }
        //4.缓存重建
        //4.1获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //4.2判断是否获取成功
            if (!isLock){
                //4.3失败 休眠并再次获取
                Thread.sleep(100);
                //再次调用方法查询-递归
                queryWithMutex(id);
            }
            //4.4成功 根据id查询数据库
            shop = getById(id);
            //5.不存在返回错误信息
            if (shop == null){
                //TODO 防止redis缓存穿透，选择缓存空字符防止继续穿透 设置过期时间防止占满内存
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //6.存在 写入redis 并设置过期时间 转换为Json格式
            String value = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key,value,CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7.释放互斥锁
            unlock(lockKey);
        }
        //8.返回shop信息
        return shop;
    }

    /**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id){
        String key = CACHE_SHOP_KEY + id;
        //1.从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isBlank(shopJson)){
            //3.不存在返回
            return null;
        }
        //4.存在缓存 需要json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //5.1未过期，返回商铺信息
            return shop;
        }
        //5.2过期 需要缓存重建
        //6.缓存重建
        //6.1获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (isLock){
            //TODO 6.3成功 开启独立线程 实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                //重建缓存
                try {
                    this.saveShopToRedis(id,30L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }

        //6.4失败，返回过期的商铺信息
        return shop;
    }

    /**
     * 封装一个尝试获取锁方法
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 封装一个释放锁方法
     * @param key
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 向redis中存储热点数据
     * @param id
     * @param expireSeconds 逻辑过期时间
     */
    public void saveShopToRedis(Long id,Long expireSeconds){
        //1.查询数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        //.plusSeconds 延长时间s
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }
}

